package net.youpoint.util;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Helper {

	/**
	 * retrieve value of cookie by key
	 * 
	 * @param key
	 * 
	 * @return value or null if key not found
	 */
	public static String getCookieValue(final String key) {
		String res = null;

		final FacesContext facesContext = FacesContext.getCurrentInstance();
		if (facesContext == null) {
			return res;
		}

		final ExternalContext externalContext = facesContext
				.getExternalContext();
		if (externalContext == null) {
			return res;
		}

		final HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext
				.getRequest();
		if (httpServletRequest == null) {
			return res;
		}

		final Cookie[] cookies = httpServletRequest.getCookies();

		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				final Cookie cookie = cookies[i];

				if (cookie.getName().equals(key)) {
					res = cookie.getValue();
					break;
				}
			}
		}

		return res;
	}

	/**
	 * set cookie value
	 * 
	 * @param key
	 * @param val
	 * @param comment
	 * @param maxAge
	 *            expiration time in seconds
	 */
	public static void setCookieValue(final String key, final String val,
			final String comment, final int maxAge) {
		final FacesContext facesContext = FacesContext.getCurrentInstance();
		if (facesContext == null) {
			return;
		}

		final ExternalContext externalContext = facesContext
				.getExternalContext();
		if (externalContext == null) {
			return;
		}

		final HttpServletResponse httpServletResponse = (HttpServletResponse) externalContext
				.getResponse();
		if (httpServletResponse == null) {
			return;
		}

		final Cookie cookie = new Cookie(key, val);
		cookie.setMaxAge(maxAge);
		cookie.setComment(comment);
		httpServletResponse.addCookie(cookie);
	}
}
